package cn.tedu.test.rpc.demo03;

import cn.tedu.test.rpc.common.IUserService;
import cn.tedu.test.rpc.common.User;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class Stub {
    public static IUserService getStub() {
        InvocationHandler handler=new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket=new Socket("127.0.0.1",8000);
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                DataOutputStream dos=new DataOutputStream(baos);
                dos.writeLong((long)args[0]);
                socket.getOutputStream().write(baos.toByteArray());
                socket.getOutputStream().flush();

                DataInputStream dis=new DataInputStream(socket.getInputStream());
                long id=dis.readLong();
                String username=dis.readUTF();
                User user=new User(id,username);
                socket.close();
                return user;
            }
        };
        Object o= Proxy.newProxyInstance(IUserService.class.getClassLoader(),new Class[]{IUserService.class},handler);
        System.out.println(o.getClass().getName());
        System.out.println(o.getClass().getInterfaces()[0]);
        return (IUserService)o;
    }
}
